#include "stdafx.h"
#include "DiskIOUtil.h"

#include "PackBuffer.h"
#include <fstream>
#include <iostream>

bool LoadFile(const char* szFileName, PackIt::CPackBuffer& packBuffer)
{
	std::ifstream fin(szFileName, std::ios::binary);
	if (!fin.is_open())
		return false;

	bool bRet = true;
	fin.seekg(0, std::ios_base::end);
	int uLen = fin.tellg();
	if (uLen > 0)
	{
		char* pBuffer = new char[uLen];
		fin.seekg(0, std::ios_base::beg);
		if ( !fin.read(pBuffer, uLen) )
		{
			std::cout << "Error~!! Load file "<<szFileName<<" failed!" << std::endl;
			bRet = false;
		}
		else
		{
			packBuffer.Pack(PackIt::PackBufferIn(pBuffer, uLen));
		}
		delete[] pBuffer;
	}
	fin.close();
	return bRet;
}

bool IsValidDirectory(const char* szDir)
{
	TCHAR path[MAX_PATH];
	int len = GetCurrentDirectory(MAX_PATH, path);
	path[len] = 0;

	bool bRet = true;
	if(!SetCurrentDirectory(szDir))
	{
		bRet = false;
	}
	SetCurrentDirectory(path);
	return bRet;
}

std::string GetFileExtension(const char* szFile)
{
	std::string file(szFile);

	std::string::size_type pos = file.rfind('.');
	if(pos != std::string::npos)
	{
		return file.substr(pos+1);
	}
	return "";
}

std::string GetFileNameOnly(const char* szPathFileName)
{
	std::string szTmp = szPathFileName;

	std::string::size_type pos = szTmp.find_last_of("\\/");
	if(pos != std::string::npos)
		szTmp = szTmp.substr(pos + 1);

	//get rid of extension
	pos = szTmp.find_last_of('.');
	if(pos != std::string::npos)
		szTmp = szTmp.substr(0, pos);
	return szTmp;
}
